#!/bin/bash

# 仓颉 Ratatui FFI 构建脚本

set -e

echo "=== 构建仓颉 Ratatui FFI 项目 ==="

# 获取脚本所在目录
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(dirname "$SCRIPT_DIR")"

echo "项目根目录: $PROJECT_ROOT"

# 构建 Rust FFI 包装器
echo "1. 构建 Rust FFI 包装器..."
cd "$PROJECT_ROOT/rust-wrapper"
cargo build --release
echo "   Rust 构建完成"

# 检查生成的库文件
if [ -f "target/release/libcangjie_ratatui_ffi.dylib" ]; then
    echo "   动态库生成成功: libcangjie_ratatui_ffi.dylib"
elif [ -f "target/release/libcangjie_ratatui_ffi.so" ]; then
    echo "   动态库生成成功: libcangjie_ratatui_ffi.so"
else
    echo "   警告: 未找到动态库文件"
fi

# 检查生成的C头文件
if [ -f "target/include/cangjie_ratatui_ffi.h" ]; then
    echo "   C头文件生成成功: cangjie_ratatui_ffi.h"
else
    echo "   警告: 未找到C头文件"
fi

# 更新仓颉项目的链接选项
echo "2. 更新仓颉项目链接选项..."
cd "$PROJECT_ROOT/cangjie-bindings"

# 根据操作系统选择正确的库文件扩展名
if [[ "$OSTYPE" == "darwin"* ]]; then
    LIB_EXT="dylib"
elif [[ "$OSTYPE" == "linux-gnu"* ]]; then
    LIB_EXT="so"
else
    LIB_EXT="so"
fi

# 更新 cjpm.toml 中的链接选项
sed -i.bak "s|link-option = \".*\"|link-option = \"-L../rust-wrapper/target/release -lcangjie_ratatui_ffi\"|" cjpm.toml
echo "   链接选项已更新"

# 构建仓颉项目
echo "3. 构建仓颉项目..."
cjpm build
echo "   仓颉构建完成"

echo "=== 构建完成 ==="
echo ""
echo "运行测试:"
echo "  cd $PROJECT_ROOT/cangjie-bindings"
echo "  cjpm run"
echo ""
echo "或者使用构建脚本运行:"
echo "  $SCRIPT_DIR/run.sh"
